package org.example.car.system.service.impl;

import org.example.car.system.domain.User;
import org.example.car.system.domain.UserPost;
import org.example.car.system.domain.UserRole;
import org.example.car.system.mapper.UserMapper;
import org.example.car.system.mapper.UserPostMapper;
import org.example.car.system.mapper.UserRoleMapper;
import org.example.car.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: cy
 * @Date: 2024/6/19 19:18
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserPostMapper userPostMapper;

    @Override
    public List<User> selectAll(User entity) {
        return userMapper.selectAll(entity);
    }

    @Override
    @Transactional
    public boolean insertUser(User entity) {
        //添加用户
        userMapper.insertUser(entity);

        //添加角色中间表
        if (entity.getRoleIds() != null && entity.getRoleIds().length > 0) {
            for (int i = 0; i < entity.getRoleIds().length; i++) {
                Integer roleIds = entity.getRoleIds()[i];
                UserRole userRole = new UserRole();
                userRole.setUserId(entity.getUserId());
                userRole.setRoleId(roleIds);
                userRoleMapper.insertUserRole(userRole);
            }
        }

        //添加岗位中间表
        if(entity.getPostIds() !=null && entity.getPostIds().length>0){
            for (int i = 0; i < entity.getPostIds().length; i++) {
                Integer postId = entity.getPostIds()[i];
                UserPost userPost = new UserPost();
                userPost.setUserId(entity.getUserId());
                userPost.setPostId(postId);
                userPostMapper.insertUserPost(userPost);
            }
        }

        return true;
    }

    @Override
    public boolean delete(Integer id) {
        return userMapper.delete(id);
    }

    @Override
    public boolean updateById(User entity) {
        return userMapper.updateById(entity);
    }

    @Override
    public User selectByName(User entity) {
        return userMapper.selectByName(entity);
    }

    @Override
    public List<User> selectAlls() {
        return userMapper.selectAlls();
    }

    @Override
    public boolean delFlag(Integer id) {
        return userMapper.delFlag(id);
    }

    @Override
    public void saveDataList(List<User> dataList) {
        userMapper.saveDataList(dataList);
    }
}
